package com.wetsoft.base.test03

object TopLevelFunction {

  def main(args: Array[String]): Unit = {

    //map函数，所有集合类型都存在map函数
    //Array类型
    Array("spark", "scala", "hadoop", "flink").map(_ * 2).foreach(println(_))
    //map 内置函数，取元组的第二个值
    List((1, "spark"), (2, "hadoop"), (3,"hive")).map(x => x._2).foreach(println(_))
    List((1, "spark"), (2, "hadoop"), (3, "hive")).map(_._1).foreach(println(_))
    List((1, "spark"), (2, "hadoop"), (3, "hive")).map(_._2).foreach(println(_))

    Map("spark" ->1,"hadoop" ->2,"flume" ->3).map(_._2)
    println("=" * 40)
    //flatMap函数，相当于flatten+map，先执行map再执行flatten
    List(List(1, 2, 3), List(2, 3, 4)).flatMap(x => x).foreach(x => print(x + " "))
    println()
    println("=" * 40)
    Array(1,2,3,4,5,6,7,8,9).filter(_ > 4).foreach(println(_))

    List("List", "Set", "Array").filter(_.length > 3).foreach(x => print(x + " "))
    println()

    Map("spark" -> 3, "hive" -> 5, "hadoop" -> 7).filter(_._2 > 3).foreach(x => print(x + " "))
    println()
    println("=" * 40)

    //reduce 前两个参数的值运算后作为下一次运算第一个值
    println(Array(1, 2, 3, 4, 5).reduce(_ * _))

    println(List("hadoop", "spark", "hive").reduce(_ + _))


    Array(1, 2, 3, 4, 5).reduce((x, y) => {
      println(x, y)
      x + y
    })


    Array(1, 2, 3, 4, 5).reduceLeft((x, y) => {
      println(x, y)
      x + y
    })
    Array(1, 2, 3, 4, 5).reduceRight((x, y) => {
      println(x, y)
      x + y
    })
    println("=" * 40)

    //fold函数
    Array(1, 2, 3, 4, 5).foldLeft(0)((x, y) => {
      println(x, y)
      x + y
    })

    println("*" * 20)
    Array(1, 2, 3, 4, 5).foldRight(10)((x, y) => {
      println(x, y)
      x + y
    })
    println(Array(1, 2, 3, 4, 5).foldLeft(0)(_ + _))
    println(Array(1, 2, 3, 4, 5).foldRight(10)(_ + _))
    println("=" * 40)
  }


}
